import { getToken, removeToken, setTimeStamp, setToken } from '@/utils/auth'
import { login, getInfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {} // 获取用户信息
  },
  mutations: {
    updateToken(state, payload) {
      state.token = payload
      setToken(payload)
    },
    //  修改用户信息
    updateUserInfo(state, payload) {
      state.userInfo = payload
    },
    //  删除用户信息
    removeUserInfo(state) {
      state.userInfo = {}
    },
    //  删除tolen
    removeToken(state) {
      state.token = ''
    }
  },
  actions: {
    async login(context, params) {
      const res = await login(params)
      context.commit('updateToken', res)
      setTimeStamp()
    },
    //  获取用户信息
    async getUserInfo({ commit }) {
      const userInfo = await getInfo()
      const result = await getUserDetailById(userInfo.userId)
      commit('updateUserInfo', { ...userInfo, ...result })
      return userInfo
    },
    //  退出登录
    logout({ commit }) {
      //  清除用户信息
      commit('removeUserInfo')
      // 清除token
      commit('removeToken')
      //  清除cookie
      removeToken()
      // 重置路由
      resetRouter()
      // 重置vuex中permission 路由数据
      commit('permission/setRoutes', [], { root: true })
    }
  }
}
